<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>管理页面</title>
    <link rel="stylesheet" href="/bootstrap.min.css">
    <link rel="stylesheet" href="/all.css">
    <link rel="stylesheet" href="/bootstrap-table.min.css">
    <style>
      body{
        background-color: #f8f8f8;
        padding: 1rem;
      }
      .search {
        padding: 0.8rem;
        border-radius: 5px;
        margin-bottom: 1rem;
        box-shadow: 1px 1px 6px -4px black;
        background-color: #ffffff;
        font-size: 14px;
        color: #555;
        display: flex;
        align-items: center;
      }
      #table{
        background-color: #ffffff;
      }
      .btn{color: #fff !important;}
      .btn-success{background-color: #1ab394 !important;}
      .btn-danger{background-color: #dc3545 !important;}
      .btn-warning{background-color: #f8ac59 !important;}
      .btn:active{opacity: 0.8;}
      input,select{
        border: 1px #aaa solid;
        border-radius: 3px;
        outline: none;
        color: #555;
        text-indent: 2px;
        min-height: 28.5px;
        min-width: 145px;
      }
      select{padding: 4px 6px;min-width: 80px;}
      .show{display: flex;}
      .show div{width: 150px;}
      .total{border: #ddd solid 1px;border-radius: 5px;padding: 5px 10px;margin-left: 40%;margin-top: 1vh;}
    </style>
  </head>
  <body>
    
    <div class="search bg-white">
      <!-- <div class="mr-2">账号：<input type="text"></div> -->
      <div class="mr-4">渠道号：<select></select></div>
      <div class="mr-2">日期：<input type="date"></div>
      <a class="btn btn-success btn-sm mr-2" onclick="searchHandle()">搜索</a>
      <a class="btn btn-warning btn-sm mr-2" onclick="location.reload()">刷新</a>
      <a class="btn btn-info btn-sm mr-2" onclick="sync()">同步状态</a>
      <a class="btn btn-info btn-sm mr-2 modal" onclick="syncdel()">同步数据</a>
      <a class="btn btn-info btn-sm" onclick="createurl()">生成链接</a>
    </div>
    <table id="table" class="bg-white"></table>

    <div class="total">
      <h5>查询结果合计:</h2>
      <div class="show">
        <div>订单量:  <span class="totle">*</span></div>
        <div>有效订单量:  <span class="real">*</span></div>
        <div>激活订单量:  <span class="active">*</span></div>
        <div>首充订单量:  <span class="pay">*</span></div>
      </div>
      
    </div>

    <script src="/jquery-3.3.1.min.js"></script>
    <script src="/popper.min.js"></script>
    <script src="/bootstrap.min.js" ></script>
    <script src="/bootstrap-table.min.js"></script>
    <script src="/zh-CN.js"></script>

    <script>
      $(async function(){
        // 日期选择框赋值今天日期
        //$('[type=date]').val(new Date().getFullYear()+'-'+(new Date().getMonth()+1+'-').padStart(3, '0')+(new Date().getDate()+'').padStart(2, '0'))
        
        // 获取数据并渲染下拉表
        await getChannelData()
        renderSelect('select',selectData)

        // 获取数据并渲染表格
        await getTableData()
        renderTable(tableData)
      })

      //定义下拉表数据和表格数据全局变量
      let selectData = [{ id: 1, name: 'TEST1' }]
      let tableData = [{ id: 1, name: 'TEST1', price: '$1' }]
      const l = console.log

      // 下拉表渲染函数
      function renderSelect(ele,data){
        let html = ['<option value="null">空</option>']
        for(let v of data){
          html.push(`<option value="${v}">${v}</option>`)
        }
        $(ele).html(html.join(""))
      }

      // 表格渲染函数
      function renderTable(data){
        let columns = [
          { field: 'ts', title: '时间戳', visible:false}, 
          { field: 'date', title: '时间',class:'text-nowrap'}, 
          { field: 'channel', title: '下游渠道' }, 
          { field: 'phone', title: '新卡号' },
          { field: 'orders', title: '下单类型',formatter(v,d,i){return v===0 ? '下单' : v===1 ? '变更' : '-'}},
          { field: 'change', title: '订单状态',formatter(v,d,i){return v===1 ? '激活' : v===6 ? '首充' : '-'}},
          { field: 'pay', title: '首充(元)',formatter(v,d,i){return v ? Math.round(v/100) : '-'}},
          { field: 'order_id', title: '订单号',class:'text-nowrap' }, 
          { field: 'post_name', title: '姓名' }, 
          { field: 'post_idnum', title: '身份证' }, 
          { field: 'post_phone', title: '联系电话' }, 
          { field: 'post_addr', title: '地址',class:'text-nowrap'}
        ]
        $('#table').bootstrapTable({data,columns,pagination:true,pageSize:7,pageList:[7,13,18,23],locale:'zh-CN'})
        $('.show .totle').text(data.length)
        $('.show .real').text(data.filter(v=>v.orders===1).length)
        $('.show .active').text(data.filter(v=>v.change===1).length)
        $('.show .pay').text(data.filter(v=>v.pay).length)
      }

      // 搜索函数
      async function searchHandle(){
        let ele = event.target
        $(ele).addClass('disabled btn-danger')
        await getTableData($('select').val(),$('[type=date').val())
        $('#table').bootstrapTable('destroy')
        renderTable(tableData)
        $(ele).removeClass('disabled btn-danger')
      }

      // 获取下拉表数据
      async function getChannelData(){
        //let res = await $.get('/manage/channeldata',{token:getQueryVariable('token')})
        //const {code,data} = res
        //if(code) return
        //if(data.length<1) return

        //data.map((v,i)=>{selectData[i] = {id:v.channel,name:v.channel}})
        //let start = +selectData[selectData.length-1].id
        
       // for(let i = 1;i<30;i++){
        //  let ch = start + i
       //   selectData.push({id:ch,name:ch})
       // }
        selectData = [0]
        for(let i = 1;i<30;i++){
          selectData.push(1e3+i)
        }
        
      }

      // 获取表格数据
      async function getTableData(channel,date){
        let options = {}
        if(channel && channel !== 'null') Object.assign(options,{channel:parseInt(channel)})
        if(date) Object.assign(options,{date}) 
        if(location.search.match('leak')) Object.assign(options,{leak:1}) 
        if(location.search.match('token')) Object.assign(options,{token:getQueryVariable('token')}) 

        let res = await $.get('/manage/carddata',options)
        const {code,data} = res
        if(code) return
        tableData = data.map(v=>{
          return Object.assign(v,{date:v.date.replace(/.{2}:/,function(v){return (+v.slice(0,-1)+8)%24+':'})})
        })
      }
      
      // 同步状态
      async function sync(){
        let change3 = await $.get('/buycardnew/msgget?status=3',{token:getQueryVariable('token')})
        let change4 = await $.get('/buycardnew/msgget?status=4',{token:getQueryVariable('token')})
        let result = await $.post('/manage/syncdata',{change3,change4,token:getQueryVariable('token')})
        result.code ? alert(result.msg || '网络忙，请刷新重试') : alert('状态同步成功')
      } 

      // 同步并删除数据
      async function syncdel(){
        let change3 = await $.get('/buycardnew/msgget?status=3',{token:getQueryVariable('token')})
        let result = await $.post('/buycardnew/syncdel',{change3,token:getQueryVariable('token')})
        result.code ? alert(result.msg || '网络忙，请刷新重试') : alert('数据同步成功')
      } 
      
      //请求参数解析
      function getQueryVariable(variable)  {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i=0;i<vars.length;i++) {
                var pair = vars[i].split("=");
                if(pair[0] == variable){return pair[1];}
        }
        return(false);
      }

      // 生成链接
      async function createurl(){
        let channel = $('select').val()
        if(confirm('你确定要为'+channel+'下游生成链接吗？')){
          let result = await $.get('/manage/createurl',{channel,token:getQueryVariable('token')})
          result.code ? alert('网络忙，请重试') : alert(result.data)
        }
        
      }
    </script>

  </body>
</html>